import { useState, useEffect } from 'react';
import { Input, Form, InputNumber, Select } from 'antd';
import './style.css';
import { AxValidator } from '../AxValidator';

const { Option } = Select;
export const AxEditableContext = React.createContext();
const EditableRow = ({ form, index, ...props }) => (
  <AxEditableContext.Provider value={form}>
    <tr {...props} />
  </AxEditableContext.Provider>
);
const Editable = ({ form, index, ...props }) => (
  <AxEditableContext.Provider value={form}>
    {props.children}
  </AxEditableContext.Provider>
);
export const AxEditableForm = Form.create()(Editable);

/** 编辑单个Table单元格Cell */
export function AxEditableCell(props) {
  const {
    editable,
    dataIndex,
    title,
    record,
    index,
    handleSave,
    children,
    required,
    pattern,
    cellType,
    validator,
    precision = 2,
    ...rest
  } = props;
  const [editing, setEditing] = useState(false);
  let input, form;

  useEffect(() => {
    if (editing && input) {
      input.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
  };

  const save = e => {
    form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      toggleEdit();
      if (handleSave) handleSave({ ...record, ...values });
    });
  };

  const cancel = e => {
    toggleEdit();
  };

  /** 获取编辑输入框 */
  const getInput = form => {
    switch (cellType) {
      case 'number':
        return (
          <InputNumber
            style={{ width: '100%' }}
            precision={precision}
            ref={node => (input = node)}
            onPressEnter={save}
            onBlur={save}
          />
        );
      default:
        return <Input ref={node => (input = node)} onPressEnter={save} onBlur={save} />;
    }
  };
  const renderCell = form => {
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              label: title,
              required,
              pattern: pattern,
              validator: validator || AxValidator,
            },
          ],
          initialValue: record[dataIndex],
        })(getInput(form))}
      </Form.Item>
    ) : (
      <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
        {children}
      </div>
    );
  };

  return (
    <td {...rest}>
      {editable ? <AxEditableContext.Consumer>{renderCell}</AxEditableContext.Consumer> : children}
    </td>
  );
}

/**
 *
 * @param showValueWrap 显示可编辑单元格的（有个边框）
 * @param editable 单元格是否可编辑
 * @param step 数字输入框的小数位数（默认：0.01）
 * @param save 保存方法
 */
export function AxEditableCellSimple(props) {
  const {
    adding,
    editing,
    editable,
    dataIndex,
    title,
    record = {},
    children,
    required,
    enumName,
    cellType,
    data = [],
    showValueWrap = false,
    validator,
    step = 0.01,
    columnsNoChange,
    save,
    autoFocus = false,
    precision = 2, //默认精度
    min = 0,
    ...rest
  } = props;

  /** 获取编辑输入框 */
  const getInput = form => {
    switch (cellType) {
      case 'select':
        return (
          <Select style={{ width: '100%' }} placeholder={`请选择${title}`}>
            {data.map((d, idx) => (
              <Option key={idx} value={d.value}>
                {d.text}
              </Option>
            ))}
          </Select>
        );
      case 'enum':
        const options = axhelper.getDicByEnumName(enumName);
        return (
          <Select style={{ width: '100%' }} placeholder={`请选择${title}`}>
            {options.map((d, idx) => (
              <Option key={idx} value={d.value}>
                {d.text}
              </Option>
            ))}
          </Select>
        );
      case 'number':
        return (
          <InputNumber
            style={{ width: '100%' }}
            step={step}
            precision={precision}
            onPressEnter={e => save && save(e, form, record)}
            onBlur={e => save && save(e, form, record)}
            autoFocus={autoFocus}
            min={min}
          />
        );
      default:
        return (
          <Input
            onPressEnter={e => save && save(e, form, record)}
            onBlur={e => save && save(e, form, record)}
            autoFocus={autoFocus}
          />
        );
    }
  };

  const renderCell = form => {
    let canChange = true;
    if (columnsNoChange && columnsNoChange.find) {
      canChange = !columnsNoChange.find(i => i == dataIndex);
    }

    return (
      <td {...rest}>
        {adding ? (
          <Form.Item style={{ margin: 0 }}>
            {form.getFieldDecorator(dataIndex, {
              rules: [
                {
                  label: title,
                  required,
                  validator: validator || AxValidator,
                },
              ],
              initialValue: record[dataIndex],
            })(getInput(form))}
          </Form.Item>
        ) : editing && canChange ? (
          <Form.Item style={{ margin: 0 }}>
            {form.getFieldDecorator(dataIndex, {
              rules: [
                {
                  label: title,
                  required,
                  validator: validator || AxValidator,
                },
              ],
              initialValue: record[dataIndex], // ? record[dataIndex].toString() : null,
            })(getInput(form))}
          </Form.Item>
        ) : showValueWrap === true && editable === true ? (
          <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }}>
            {children}
          </div>
        ) : (
          children
        )}
      </td>
    );
  };

  return <AxEditableContext.Consumer>{renderCell}</AxEditableContext.Consumer>;
}

/**
 *
 * @param showValueWrap 显示可编辑单元格的（有个边框）
 * @param editable 单元格是否可编辑
 * @param step 数字输入框的小数位数（默认：0.01）
 * @param save 保存方法
 */
export function AxEditableSimple(props) {
  const {
    adding,
    editing,
    editable,
    dataIndex,
    title,
    record = {},
    children,
    required,
    enumName,
    cellType,
    data = [],
    showValueWrap = false,
    validator,
    step = 0.01,
    columnsNoChange,
    save,
    autoFocus = false,
    precision = 2, //默认精度
    min = 0,
    ...rest
  } = props;

  /** 获取编辑输入框 */
  const getInput = form => {
    switch (cellType) {
      case 'select':
        return (
          <Select style={{ width: '100%' }} placeholder={`请选择${title}`}>
            {data.map((d, idx) => (
              <Option key={idx} value={d.value}>
                {d.text}
              </Option>
            ))}
          </Select>
        );
      case 'enum':
        const options = axhelper.getDicByEnumName(enumName);
        return (
          <Select style={{ width: '100%' }} placeholder={`请选择${title}`}>
            {options.map((d, idx) => (
              <Option key={idx} value={d.value}>
                {d.text}
              </Option>
            ))}
          </Select>
        );
      case 'number':
        return (
          <InputNumber
            style={{ width: '100%' }}
            step={step}
            precision={precision}
            onPressEnter={e => save && save(e, form, record)}
            onBlur={e => save && save(e, form, record)}
            autoFocus={autoFocus}
            min={min}
          />
        );
      default:
        return (
          <Input
            onPressEnter={e => save && save(e, form, record)}
            onBlur={e => save && save(e, form, record)}
            autoFocus={autoFocus}
          />
        );
    }
  };

  const renderCell = form => {
    let canChange = true;
    if (columnsNoChange && columnsNoChange.find) {
      canChange = !columnsNoChange.find(i => i == dataIndex);
    }

    return (
      <div {...rest}>
        {adding ? (
          <Form.Item style={{ margin: 0 }}>
            {form.getFieldDecorator(dataIndex, {
              rules: [
                {
                  label: title,
                  required,
                  validator: validator || AxValidator,
                },
              ],
              initialValue: record[dataIndex],
            })(getInput(form))}
          </Form.Item>
        ) : editing && canChange ? (
          <Form.Item style={{ margin: 0 }}>
            {form.getFieldDecorator(dataIndex, {
              rules: [
                {
                  label: title,
                  required,
                  validator: validator || AxValidator,
                },
              ],
              initialValue: record[dataIndex], // ? record[dataIndex].toString() : null,
            })(getInput(form))}
          </Form.Item>
        ) : showValueWrap === true && editable === true ? (
          <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }}>
            {children}
          </div>
        ) : (
          children
        )}
      </div>
    );
  };

  return <AxEditableContext.Consumer>{renderCell}</AxEditableContext.Consumer>;
}
